/*!
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *
 *    Author: flareguner
 *    E-Mail: flareguner@gmail.com
 *    Years: 2010-2011
 */


#include "shortcutwidget.h"
#include <QtGui/QKeySequence>
#include <QtGui/QKeyEvent>
#include <QtGui/QLineEdit>
#include <QtGui/QToolButton>
#include <QtGui/QHBoxLayout>
#include <QtCore/QEvent>


ShortcutWidget::ShortcutWidget(QWidget *parent) :
    QWidget(parent)
{
    createUi();

    shortcutLine->installEventFilter(this);

    connect(clearButton, SIGNAL(clicked()),shortcutLine, SLOT(clear()));
}

QKeySequence ShortcutWidget::getShortcut() const {
    return QKeySequence(shortcutLine->text());
}

void ShortcutWidget::setShortcut(const QKeySequence &seq) {
    shortcutLine->setText(seq.toString());
}


bool ShortcutWidget::eventFilter(QObject *obj, QEvent *event) {

    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        int key = keyEvent->text().length() == 1 ? keyEvent->key() : 0;
        int mod = keyEvent->modifiers() & ~Qt::KeypadModifier;
        shortcutLine->setText(QKeySequence(key + mod).toString());

        return true;
    }
  else
      return QObject::eventFilter(obj, event);

  return true;
}


void ShortcutWidget::createUi() {
    shortcutLine = new QLineEdit(this);
    clearButton = new QToolButton(this);

    mainLayout = new QHBoxLayout;

    mainLayout->addWidget(shortcutLine);
    mainLayout->addWidget(clearButton);

    this->setLayout(mainLayout);
}
